package com.example.chat.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.chat.beans.Mate;
import com.example.chat.beans.Record;
import com.example.chat.beans.Video;
import com.example.chat.mapper.*;
import com.example.chat.result.ApiResult;
import com.example.chat.result.RecordStatusResult;
import com.example.chat.result.RecordStopResult;
import com.example.chat.utils.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling
public class MySchedulerTask {
    @Resource
    TokenMapper tokenMapper;
    @Resource
    Global global;
    @Resource
    ConfigMapper configMapper;
    @Resource
    MateMapper mateMapper;
    @Resource
    RecordMapper recordMapper;
    @Resource
    VideoMapper videoMapper;
    @Resource
    OssUtil ossUtil;

    @Async
    @Scheduled(fixedRate = 10 * 1000)
    public void refreshConfig() {
        global.setConfig(configMapper.selectById(1));
    }

    @Async
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void deleteToken() {
        tokenMapper.deleteLate(System.currentTimeMillis() - 5 * 24 * 60 * 60 * 1000);
    }

    @Async
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void expireChat() {
        List<Mate> mateList = mateMapper.selectExpire(System.currentTimeMillis());
        for (Mate mate : mateList) {
            mate.setStatus(4);
            mateMapper.updateById(mate);
        }
    }

    @Async
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void expireFile() {
        if (global.getConfig() != null) {
            List<Video> videos = videoMapper.selectExpire(System.currentTimeMillis() - (global.getConfig().getMaxSaveTime() * 30 * 24 * 60 * 60 * 1000L));
            for (Video video : videos) {
                videoMapper.deleteById(video.getId());
                ossUtil.deleteFile("", video.getFilePath());
            }
        }
    }

    @Async
    @Scheduled(fixedRate = 12 * 60 * 60 * 1000)
    public void expireScreen() {
        long time = System.currentTimeMillis() - 86400000L;
        String date = global.getSdf().format(new Date(time));
        FileHandleUtil.delete("screen/" + date + "/");//photo/20230701/1688183767879_13.jpg
    }


    @Async
    @Scheduled(fixedRate = 30 * 1000)
    public void expireRecord() {
        List<Record> recordList = recordMapper.selectAllRecord();
        for (Record record : recordList) {
            String url = "https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/resourceid/" + record.getResourceId() + "/sid/" + record.getSid() + "/mode/mix/query";
            System.out.println("url:" + url);
            ApiResult<String> data = OkHttpUtils.builder().url(url)
                    .addHeader("Authorization", Base64Encoding.authCode())
                    .addHeader("Content-Type", "application/json")
                    .get()
                    .sync();
            if (data != null) {
                int code = data.getStatus();
                if (code == 200) {
                    System.out.println(data.getData());
                    RecordStatusResult recordStatusResult = JSON.parseObject(data.getData(), RecordStatusResult.class);
                    if (recordStatusResult != null) {
                        if (recordStatusResult.getServerResponse().sliceStartTime != 0 &&
                                System.currentTimeMillis() - recordStatusResult.getServerResponse().sliceStartTime >
                                        global.getConfig().getLongRecord() * 60 * 60 * 1000L) {
                            JSONObject clientRequest = new JSONObject();
                            clientRequest.put("async_stop", false);
                            ApiResult<String> stopData = OkHttpUtils.builder().url("https://api.agora.io/v1/apps/" + global.getConfig().getShengwangAppId() + "/cloud_recording/resourceid/" + record.getResourceId() + "/sid/" + record.getSid() + "/mode/mix/stop")
                                    .addHeader("Authorization", Base64Encoding.authCode())
                                    .addHeader("Content-Type", "application/json")
                                    .addParam("cname", record.getChannel())
                                    .addParam("uid", record.getUid())
                                    .addParam("clientRequest", clientRequest)
                                    .post(true)
                                    .sync();
                            if (stopData != null) {
                                code = data.getStatus();
                                if (code == 200) {
                                    RecordStopResult recordStopResult = JSON.parseObject(data.getData(), RecordStopResult.class);
                                    if (recordStopResult != null) {
                                        System.out.println(data.getData());
                                        List<RecordStopResult.File> fileList = recordStopResult.getServerResponse().fileList;
                                        for (RecordStopResult.File file : fileList) {
                                            if (file.fileName.endsWith(".mp4")) {
                                                Video video = new Video();
                                                video.setFilePath(file.fileName);
                                                video.setCreateAdmin(record.getCreateAdmin());
                                                video.setChatAdminId(0);
                                                video.setCreateTime(System.currentTimeMillis());
                                                videoMapper.insert(video);
                                            }
                                        }
                                        record.setStatus(3);
                                        recordMapper.updateById(record);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (code == 404) {
                        record.setStatus(3);
                        recordMapper.updateById(record);
                    }
                }
            } else {
                record.setStatus(3);
                recordMapper.updateById(record);
            }
        }
    }
}
